package com.bng8.superstar_cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bng8.superstar_cms.domain.common.PageQuery;
import com.bng8.superstar_cms.domain.common.PageResult;
import com.bng8.superstar_cms.domain.dto.SupChallengerDTO;
import com.bng8.superstar_cms.domain.dto.SupUserDTO;
import com.bng8.superstar_cms.domain.dto.SupUserQueryDTO;
import com.bng8.superstar_cms.domain.entity.SupChallengerDO;
import com.bng8.superstar_cms.domain.entity.SupUserDO;
import com.bng8.superstar_cms.mapper.SupChallengerMapper;
import com.bng8.superstar_cms.mapper.SupUserMapper;
import com.bng8.superstar_cms.service.SupUserService;
import com.bng8.superstar_cms.util.ShaUtils;
import com.bng8.superstar_cms.util.ValidatorUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author 20393
 * @description 针对表【sup_user(用户表)】的数据库操作Service实现
 * @createDate 2023-08-15 14:07:57
 */
@Service
public class SupUserServiceImpl extends ServiceImpl<SupUserMapper, SupUserDO>
        implements SupUserService {
    @Autowired
    private SupUserMapper supUserMapper;

    @Autowired
    private SupChallengerMapper challengerMapper;

    private SupUserDO supUserDO;

    private SupChallengerDO challengerDO;

    private SupUserDTO supUserDTO1;

    private SupChallengerDTO challenger;

    /**
     * 新增用户信息
     *
     * @param supUserDTO 前端传入数据
     * @return 有返回结果
     */
    @Override
    public int save(SupUserDTO supUserDTO, HttpServletRequest request) throws Exception {
        //密码加密处理
        String wrap = StringUtils.wrap(ShaUtils.getSalt(), supUserDTO.getPassword());
        String encrypt = ShaUtils.encrypt(wrap);
        supUserDTO.setPassword(encrypt);
        challenger = supUserDTO.getChallenger();
        BeanUtils.copyProperties(challenger, challengerDO);
        challengerMapper.insert(challengerDO);
        BeanUtils.copyProperties(supUserDTO, supUserDO);
        if (StringUtils.isBlank(supUserDO.getNickName())) {
            supUserDO.setNickName("rookie");
        }
        //查询用户输入的用户名是否已存在
        List<SupUserDO> userNameList = supUserMapper
                .selectList(new QueryWrapper<SupUserDO>().eq("user_name", supUserDTO.getUserName()));
        if (userNameList.size() == 0) {
            supUserDO.setCreator(request.getRemoteAddr());
            supUserDO.setOperator(request.getRemoteAddr());
            return supUserMapper.insert(supUserDO);
        } else {
            return -1;
        }
    }

    /**
     * 更新用户信息
     *
     * @param id
     * @param supUserDTO
     * @return
     */
    @Override
    public int update(Long id, SupUserDTO supUserDTO, HttpServletRequest request) {
        boolean repeat = repeat(id, supUserDTO);
        if (repeat) {
            BeanUtils.copyProperties(supUserDTO, supUserDO);
            supUserDO.setOperator(request.getRemoteAddr());
            return supUserMapper.updateById(supUserDO);
        } else {
            return 1;
        }
    }

    /**
     * 分页查询用户信息
     *
     * @param pageQuery
     * @return
     */
    @Override
    public PageResult<List<SupUserDTO>> query(PageQuery<SupUserQueryDTO> pageQuery) {
        // 手动校验功能
        ValidatorUtils.validate(pageQuery);
        // 参数构造
        Page page = new Page(pageQuery.getPageNo(),
                pageQuery.getPageSize());
        SupUserDO query = new SupUserDO();
        BeanUtils.copyProperties(pageQuery.getQuery(), query);
        // TODO 如果属性不一致，需要做特殊处理
        QueryWrapper<SupUserDO> queryWrapper =
                new QueryWrapper<SupUserDO>()
                        .like("nick_name", query.getNickName());
        // 查询
        IPage<SupUserDO> userDOIPage = supUserMapper.selectPage(page, queryWrapper);
        // 结果解析
        PageResult pageResult = new PageResult();
        pageResult.setPageNo((int) userDOIPage.getCurrent());
        pageResult.setPageSize((int) userDOIPage.getSize());
        pageResult.setTotal(userDOIPage.getTotal());
        pageResult.setPageNum(userDOIPage.getPages());
        // 对数据进行转换
        List<SupUserDTO> userDTOList = Optional
                .ofNullable(userDOIPage.getRecords())
                .map(List::stream)
                .orElseGet(Stream::empty)
                .map(userDO -> {
                    SupUserDTO userDTO = new SupUserDTO();
                    SupChallengerDTO supChallengerDTO = new SupChallengerDTO();
                    BeanUtils.copyProperties(userDO, userDTO);
                    supChallengerDTO.setChallenger(userDO.getChallenger());
                    userDTO.setChallenger(supChallengerDTO);
                    return userDTO;
                })
                .collect(Collectors.toList());
        pageResult.setData(userDTOList);
        return pageResult;
    }

    /**
     * 如果数据未修改，则返回false
     *
     * @param id
     * @param supUserDTO
     * @return
     */
    private boolean repeat(Long id, SupUserDTO supUserDTO) {
        supUserDO = supUserMapper.selectById(id);
        //根据id查询用户信息
        BeanUtils.copyProperties(supUserDO, supUserDTO1);
        return !supUserDTO.equals(supUserDTO1) && supUserDTO.getUserName().equals(supUserDO.getUserName());
    }
}




